package com.geekaca;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.geekaca.pojo.Brand;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

public class BlurQuery {
    public static void main(String[] args) throws Exception {
        //1.加载配置文件
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/main/resources/druid.properties"));
        //2, 构造连接池对象
        /**
         * DataSource 是Java官方的规范,数据库连接池规范
         */
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //3 从数据库连接池获取连接
        Connection conn = dataSource.getConnection();

        Scanner scanner = new Scanner(System.in);
        ArrayList<Brand> brandList = new ArrayList<>();

        brandList = blurQuery(conn, brandList,scanner);
        if (brandList.size()>0){
            System.out.print("查询到数据: ");
            for (int i = 0; i < brandList.size(); i++) {
                System.out.println(brandList.get(i));
            }
        }

    }
    public static ArrayList<Brand> blurQuery(Connection conn, ArrayList<Brand> brandList, Scanner scanner) throws SQLException {

        String sql = "select * from brands.tb_brand where brand_name like ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        System.out.println("请输入查询的品牌: ");
        String blurBrand = scanner.next();
        blurBrand = "%"+blurBrand+"%";
        pstmt.setString(1,blurBrand);

        ResultSet resultSet = pstmt.executeQuery();
        while (resultSet.next()){
            int id = resultSet.getInt("id");
            String brandName = resultSet.getString("brand_name");
            String companyName = resultSet.getString("company_name");
            int ordered = resultSet.getInt("ordered");
            String description = resultSet.getString("description");
            int status = resultSet.getInt("status");
            Brand brand = new Brand(id, brandName, companyName, ordered, description, status);
            brandList.add(brand);
        }
        return brandList;


    }


}
